package net.huanger.opendir.popup.actions;


import java.awt.Desktop;
import java.io.File;
import java.io.IOException;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;


public class OpenDirAction implements IObjectActionDelegate
{

  private Shell shell;

  private File openFile;

  /**
   * Constructor for Action1.
   */
  public OpenDirAction()
  {
    super();
  }

  /**
   * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
   */
  public void setActivePart(IAction action, IWorkbenchPart targetPart)
  {
    shell = targetPart.getSite().getShell();
  }

  /**
   * @see IActionDelegate#run(IAction)
   */
  public void run(IAction action)
  {
    if (openFile == null)
      return;
    if (Desktop.isDesktopSupported())
    {
      try
      {
        Desktop.getDesktop().open(openFile);
      }
      catch (IOException e)
      {
        e.printStackTrace();
      }
    }
    else
    {
      MessageDialog.openInformation(shell, "Not Support!", "This need java's DesktopSupport!.");
    }

  }

  /**
   * @see IActionDelegate#selectionChanged(IAction, ISelection)
   */
  public void selectionChanged(IAction action, ISelection selection)
  {
    if(!(selection instanceof StructuredSelection)){
      openFile=null;
      return;
    }
    StructuredSelection sel=(StructuredSelection)selection;
    if(sel.size()!=1){
      openFile=null;
      return;
    }
    IResource resource=null;
    Object obj=sel.getFirstElement();
    if(obj instanceof IResource){
      resource=(IResource)obj;
    }else if(obj instanceof IAdaptable){
      IAdaptable adp=(IAdaptable)obj;
      resource=(IResource)adp.getAdapter(IResource.class);
    }
    if(resource!=null){
      if (resource instanceof IFile)
      {
        resource = ((IFile)resource).getParent();
      }
      openFile=resource.getLocation().toFile();
    }else{
      openFile=null;
    }
  }

}
